import 'package:flutter/material.dart';
import 'package:flutter_image/network.dart';
import 'package:flutter_mwm/base/base.dart';
import 'package:flutter_mwm/impl/http.dart';
import 'package:flutter_mwm/ui/weather.dart';
import 'package:flutter_mwm/widget/text.dart';
import '../ui/personal.dart';
import '../ui/qrcode.dart';
import '../beans/bean.dart';
import '../impl/impl.dart';
import '../util/util.dart';
import '../widget/widget.dart';

class MainHome extends BaseWidget<MainHome> {
  final AccountBean accountBean;
  final String imgUrl;

  const MainHome({this.accountBean, this.imgUrl});

  @override
  State<StatefulWidget> createState() {
    return _MainState();
  }
}

class _MainState extends StateBase<MainHome> implements HttpCallbackImpl {
  var username = '', iconUrl = '';
  var cityName = '西安';
  var accountBean;

  @override
  void initState() {
    super.initState();
    accountBean = widget.accountBean;
    if (null != accountBean) {
      username = accountBean.username;
    }
    showAvatar();
    _queryByAccount();
  }

  Future<Null> showAvatar() async {
    iconUrl = await HttpKit.getInstance()
        .getIcon(method: 'showAvatar', username: username);
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    String signature = null == accountBean ? "" : accountBean.signature;
    String signStr = TextUtils.isEmpty(signature) ? "此人很懒..." : signature;
    Color color =
        TextUtils.isEmpty(signature) ? Colors.grey[300] : Colors.white;
    return Scaffold(
        appBar: AppBar(
          backgroundColor: Color(0xFF051728),
          centerTitle: true,
        ),
        drawer: Drawer(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              UserAccountsDrawerHeader(
                decoration: BoxDecoration(color: Color(0xFF051728)),
                accountName: Text(username),
                accountEmail: Text(signStr, style: TextStyle(color: color)),
                otherAccountsPictures: <Widget>[
                  _qrView(),
                ],
                currentAccountPicture: _iconView(),
              ),
              _menuView('1', null),
              _flexView(),
              _weatherView(),
            ],
          ),
        ),
        body: Container(
          child: Text('MainIndex'),
        ));
  }

  /*圆形头像*/
  Widget _iconView() {
    double size = 80;
    ImageProvider imageProvider =
        TextUtils.isEmpty(username) || TextUtils.isEmpty(iconUrl)
            ? AssetImage('images/icon.png')
            : NetworkImageWithRetry(iconUrl);

    Widget inside = Container(
        width: size - 2,
        height: size - 2,
        margin: EdgeInsets.all(2),
        child: CircleAvatar(
            radius: size - 2,
            backgroundImage: imageProvider,
            backgroundColor: Colors.green));
    Widget outside = ClickLayout(
      width: size,
      height: size,
      child: CircleAvatar(
          radius: size, child: inside, backgroundColor: Colors.white),
      onPressed: _onPersonalResult,
    );

    return outside;
  }

  void _onPersonalResult() {
    Navigator.push(
            context,
            MaterialPageRoute(
                builder: (_) => PersonalHome(accountBean: accountBean)))
        .then((value) {
      //onActivityResult之后
      //重新加载用户头像
      showAvatar();
      _queryByAccount();
    });
  }

  Future<Null> _queryByAccount() async {
    Map<String, String> bodyParams = {'username': username};
    var http = HttpKit.getInstance();
    http.callback(this);
    http.execute(method: 'queryUser', paramBody: bodyParams);
  }

  var imgUrl = 'images/qr_normal.png';

  /*二维码*/
  Widget _qrView() {
    return ClickLayout(
        child: Image.asset(imgUrl),
        onPressed: () {
          Navigator.push(
              context,
              MaterialPageRoute(
                  builder: (_) => QrCodeHome(username: username)));
        },
        onHighlightChanged: (bool changed) {
          setState(() {
            imgUrl = changed ? 'images/qr_pressed.png' : 'images/qr_normal.png';
          });
        });
  }

  /*侧滑菜单*/
  Widget _menuView(String text, VoidCallback callBack) {
    return ClickLayout(
      child: Text(text),
      onPressed: callBack,
    );
  }

  /*用来将weatherView放置在右下角*/
  Widget _flexView() {
    return Expanded(
      child: Text(''),
    );
  }

  /*底部天气☁️*/
  Widget _weatherView() {
    return Row(mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[
      Container(
        child: ClickLayout(
            onPressed: _weather,
            child: Column(
              children: <Widget>[
                TextView(
                  '-2˚',
                  /*style: TextStyle(
                      color: Colors.indigoAccent,
                      fontSize: 18.0,
                      fontWeight: FontWeight.bold),*/
                  textAlign: TextAlign.right,
                  //alignment: Alignment.centerRight,

                  margin: EdgeInsets.only(bottom: 4.0),
                  padding: EdgeInsets.only(left: 15.0, right: 15.0, top: 8.0),
                ),
                TextView(
                  cityName,
                  //style: TextStyle(color: Colors.black, fontSize: 18.0),
                  textAlign: TextAlign.right,
                  padding:
                      EdgeInsets.only(left: 15.0, right: 15.0, bottom: 10.0),
                  //alignment: Alignment.centerRight,
                ),
              ],
            )),
      ),
    ]);
  }

  void _weather() {
    Navigator.push(context, MaterialPageRoute(builder: (_) => WeatherHome()))
        .then((value) {
      if (!TextUtils.isEmpty(value)) {
        setState(() {
          cityName = value;
        });
      }
    });
  }

  @override
  void onResult(int what, Object tag, String result) {
    try {
      ReturnAccountBean returnAccountBean = ReturnAccountBean.json2Bean(result);
      if (null == returnAccountBean) {
        return;
      }
      String code = returnAccountBean.code;
      String message = returnAccountBean.message;
      if (!TextUtils.equals("1", code)) {
        ToastUtil.show(context, message);
        return;
      }
      AccountBean tempBean = returnAccountBean.obj;
      setState(() {
        accountBean = tempBean;
      });
    } catch (error) {
      onError(what, tag, error);
    }
  }

  @override
  void onError(int what, Object tag, String error) {
    showErrorPromptDialog("", error);
  }
}
